<template>
<div class="order">
  <van-nav-bar style="margin-bottom:0;" title="订单确认" left-arrow @click-left="goback"/>
  <van-cell-group>
      <van-cell v-if="checkedAddress" isLink @click="goAddressList()" title="收货地址">
      <div slot="label">
        <div>
         <span>{{ checkedAddress.name }} </span>
         <span>{{ checkedAddress.tel }} </span>
      </div>
      <div>
        {{ checkedAddress.addressDetail }}
      </div>
      </div>
    </van-cell>
  </van-cell-group>

  <!-- <van-cell-group>
    <van-cell class="order-coupon" title="优惠券" is-link :value="getCouponValue()" @click="getCoupons" />
  </van-cell-group> -->

<!-- 优惠券列表 -->
<!-- <van-popup v-model="showList" position="bottom">
  <van-coupon-list
    :coupons="coupons"
    :chosen-coupon="chosenCoupon"
    :disabled-coupons="disabledCoupons"
    @change="onChange"
    @exchange="onExchange"
  />
</van-popup> -->

    <van-card
      v-for="item in checkedGoodsList"
      :key="item.id"
      :title="item.goodsName"
      :num="item.number"
      :price="item.price +'.00'"
      :thumb="item.picUrl"
    >
      <div slot="desc">
        <div class="van-card__desc">
          <van-tag plain style="margin-right:6px;" v-for="(spec, index) in item.specifications" :key="index">
            {{spec}}
          </van-tag>
        </div>
      </div>
    </van-card>

    <van-cell-group>
      <van-cell title="商品金额">
        <span class="red">{{goodsTotalPrice * 100 | yuan}}</span>
      </van-cell>
      <!-- <van-cell title="邮费">
        <span class="red">{{ freightPrice * 100| yuan}}</span>
      </van-cell> -->
      <van-cell title="账号余额">
        <span class="red">{{ balance * 100| yuan}}</span>
      </van-cell>
      <van-field v-model="yue" placeholder="输入抵扣金额（元）" label="使用余额">
      </van-field> 
      <!-- <van-cell title="优惠券">
        <span class="red">-{{ couponPrice * 100| yuan}}</span>
      </van-cell> -->
      <!-- <van-field v-model="message" placeholder="请输入备注" label="订单备注"> -->
      <template slot="icon">{{message.length}}/50</template>
      </van-field>     
      <div>
        <van-cell v-show="!eyu">
          <!-- 使用 title 插槽来自定义标题 -->
          <template slot="title">
            <van-tag type="danger" plain>满1000减50</van-tag>
          </template>
        </van-cell>
        <van-cell title="支付方式">
        </van-cell>
        <van-radio-group v-model="radio">
          <van-cell-group class="pay-list">
            <van-cell title="微信支付" clickable @click="payHandle('微信支付')">
              <img class="pay-icon" src='http://www.dtw360.cn/static/images/cart-wechat.png'>
              <van-radio slot="right-icon" name="微信支付" />
            </van-cell>
            <van-cell title="支付宝支付" clickable @click="payHandle('支付宝支付')">
              <img class="pay-icon" src='http://www.dtw360.cn/static/images/cart-alipay.png'>
              <van-radio slot="right-icon" name="支付宝支付" />
            </van-cell>
            <van-cell title="银联支付" clickable @click="payHandle('银联支付')">
              <img class="pay-icon" src='http://www.dtw360.cn/static/images/cart-yinlian.png'>
              <van-radio slot="right-icon" name="银联支付" />
            </van-cell>
            <van-cell title="花呗分期" clickable @click="payHandle('花呗分期')">
              <img class="pay-icon" src='http://www.dtw360.cn/static/images/cart-huabei.png'>
              <van-radio slot="right-icon" name="花呗分期" />
            </van-cell>
            
          </van-cell-group>
        </van-radio-group>
        <van-row v-if="huabeiShow" gutter="10" style="margin: 10px 10px;padding-bottom: 20px;">
          <van-col @click="clickHuabei(item.hbFqNum)" v-for="(item, i) in huabei" :key="i" class="huabei" :class="[huabeiSel===item.hbFqNum?'selected':'']" span="8">
            <div class="fenqi">
              <div class="tit"><span>{{item.hbFqNum}}</span>期</div>
              <div class="tit2">￥<span>{{item.prinAndFee}}</span>X{{item.hbFqNum}}</div>
              <div>总计：<br>￥<span>{{(item.prinAndFee*item.hbFqNum).toFixed(2)}}</span></div>
            </div>
          </van-col>
        </van-row>
      </div> 
    </van-cell-group>

    <van-submit-bar
      :price="actualPrice*100"
      label="总计："
      buttonText="支付"
      :disabled="isDisabled"
      @submit="onSubmit"
    />
</div>
</template>

<script>
import { Card, Tag, ard, Field, SubmitBar, Toast, NavBar, RadioGroup, Radio, Row, Col, Dialog  } from 'vant';
import { CouponCell, CouponList, Popup } from 'vant';
import { cartCheckout, orderSubmit, couponSelectList, orderAlipayHbInfo, orderAlipay, orderPrepay, getUserOrderStatus, userCheckAgree, orderPayByQuickApply } from '@/api/api';
import { getLocalStorage, setLocalStorage } from '@/utils/local-storage';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      eyu: true,
      eyu1: '',
      eyu2: '',
      checkedGoodsList: [],
      checkedAddress: {},
      availableCouponLength: 0, // 可用的优惠券数量
      goodsTotalPrice: 0, //商品总价
      balance: 0, //可用余额
      freightPrice: 0, //快递费
      couponPrice: 0, //优惠券的价格
      grouponPrice: 0, //团购优惠价格
      orderTotalPrice: 0, //订单总价
      actualPrice: 0, //实际需要支付的总价
      message: '',
      yue: '',
      huabei: [],
      huabeiShow: false,
      huabeiSel: 3,
      radio: '微信支付',
      isDisabled: false,
      showList: false,
      chosenCoupon: -1,
      coupons: [],
      disabledCoupons: [],
      isMj: false
    };
  },
  created() {
    this.init();
  },

  watch: {
    yue() {
      if(!/^\d+(\.\d*)?$/.test(this.yue)) {
        Toast('请输入数字')
        this.yue = ''
      }
      if(this.yue > this.balance) {
        Toast('抵扣金额不能大于余额')
        this.yue = this.balance
      }
      if(this.yue > this.goodsTotalPrice) {
        Toast('抵扣金额不能大于实际金额')
        this.yue = this.goodsTotalPrice
      }
      this.actualPrice = this.goodsTotalPrice - this.yue
      this.huabeiShowFun()
    }
  },

  methods: {
    clickHuabei (i) {
      this.huabeiSel = i
    },
    payHandle(pay) {
      this.radio = pay
      if (pay === '花呗分期') {
        this.huabeiShow = true
        this.huabeiShowFun()
      } else {
        this.huabeiShow = false
        if(pay === '银联支付') {
          userCheckAgree().then(res => {
            // console.log(res, 'pay')
            if (res.data.data !== true) {
              Dialog.confirm({
                title: '提示',
                message: '是否绑定银行卡',
              }).then(() => {
                  // on confirm
                 this.$router.push('/order/agreeapply')
              }).catch(() => {
                  // on cancel
                  this.radio = '微信支付'
              });
            }
          })
          
        }
      }
    },
    huabeiShowFun() {
      orderAlipayHbInfo({amount: this.actualPrice}).then(res => {
        // console.log(this.actualPrice, 'huabei')
        this.huabei = res.data
      })
    },
    onSubmit() {
      const {AddressId, CartId, CouponId} = getLocalStorage('AddressId', 'CartId', 'CouponId');
      if (AddressId === null || AddressId === '0' || AddressId === 0) {
        Toast.fail('请设置收货地址');
        return;
      }
      this.isDisabled = true;
      orderSubmit({
        addressId: AddressId,
        cartId: CartId,
        couponId: CouponId,
        orderSource: 'APP',
        integralPrice: this.yue,
        payType: this.radio,
        grouponLinkId: 0,
        grouponRulesId: 0,
        message: this.message
      }).then(res => {
        // console.log(res)
        // 下单成功，重置下单参数。
        let orderId = res.data.data.orderId;
        setLocalStorage({AddressId: 0, CartId: 0, CouponId: 0});
        if(this.radio === '支付宝支付' || this.radio === '花呗分期') {
          let hbFqNum = ''
          if (this.radio === '花呗分期') {
              hbFqNum = this.huabeiSel
          }
          orderAlipay({orderId: orderId, hbFqNum: hbFqNum}).then(info => {
            // console.log(info, 'ali')
            if(info.data.errno === 0) {
              window.cordova.plugins.alipay.payment(info.data.data, (e) => {
                this.$toast('支付成功')
                // 支付成功
                this.$router.push('/user/order/list/2')
              }, (e) => {
                // TODO 支付失败
                // console.log('支付失败' + e.resultStatus)
                this.$toast('支付失败')
                this.$router.push('/user')
              })

            } else if (info.data.errno === 1) {
              this.$toast('支付成功')
              this.$router.push('/user/order/list/2')
            } else {
              this.isDisabled = false;
              this.$toast(info.data.errmsg);
              this.$router.push('/user')
            }
          })
          this.$router.push('/user')
        } else if (this.radio === '微信支付') {
          
          orderPrepay({orderId: orderId}).then(info => {
            // console.log(info)
            if(info.data.errno === 0) {
              var params = {
                appid: info.data.data.appId, // appId
                partnerid: info.data.data.partnerId, // merchant id
                prepayid: info.data.data.prepayId, // prepay id
                noncestr: info.data.data.nonceStr, // nonce
                backage: 'Sign=WXPay',
                timestamp: info.data.data.timeStamp, // timestamp
                sign: info.data.data.sign // signed string
              }
              window.Wechat.sendPaymentRequest(params, function () {
                this.$toast('支付成功')
                this.$router.push('/user/order/list/2')
              }, function (reason) {
                this.$toast('Failed: ' + reason)
                this.$router.push('/user/order/list/1')
              })
            } else if (info.data.errno === 1) {
              this.$toast('支付成功')
              this.$router.push('/user/order/list/2')
            } else {
              this.isDisabled = false;
              this.$toast(info.data.errmsg);
              this.$router.push('/user')
            }
          })
          this.$router.push('/user')
        } else if(this.radio === '银联支付') {
          if(res.data.errno === 0) {
            var params = {
                orderId : res.data.data.orderId,
                orderSource : 'APP'
              }
            orderPayByQuickApply(params).then(info => {
              if (info.data.data.resultCode === '1999')
              {
                setLocalStorage({orderId: res.data.data.orderId});
                setLocalStorage({thpinfo: info.data.data.thpinfo});
                this.$router.push('/order/smsConfirm')
              }
            })
          }
        }
      }).catch(error => {
        this.isDisabled = false;
        this.$toast("下单失败");
      })

    },
    delayer (action, delay = 600) {
      let timer = -1;
      return nv => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          action(nv);
        }, delay);
      };
    },
    goAddressList() {
      this.$router.push({
        path: '/user/address'
      });
    },
    getCouponValue() {
      if(this.couponPrice !== 0 ){
        return "-¥" + this.couponPrice + ".00元"
      }
      if(this.availableCouponLength !== 0){
        return this.availableCouponLength + "张可用"
      }
      return '没有可用优惠券'
    },
    goback() {
      this.$router.go(-1);
    },
    getCoupons() {
      const {AddressId, CartId, CouponId} = getLocalStorage('AddressId', 'CartId', 'CouponId');
      couponSelectList({cartId: CartId, grouponRulesId: 0}).then(res => {
        var cList = res.data.data
        this.coupons = []
        for(var i = 0; i < cList.length; i++){
          var c = cList[i]

          var coupon = {
            id: c.id,
            name: c.name,
            condition: c.min,
            value: c.discount * 100,
            description: c.desc,
            startAt: new Date(c.startTime).getTime()/1000,
            endAt: new Date(c.endTime).getTime()/1000,
            valueDesc: c.discount,
            unitDesc: '元'            
          }
          this.coupons.push(coupon)

          if(c.id === this.couponId){
            this.chosenCoupon = i;
            break;
          }
        }
        
        this.showList = true
      })
    },
    init() {
      const {AddressId, CartId, CouponId} = getLocalStorage('AddressId', 'CartId', 'CouponId');

      cartCheckout({cartId: CartId, addressId: AddressId, couponId: CouponId, grouponRulesId: 0}).then(res => {
          // console.log(res)
          if (res.data.errno === 0)
          {
            var data = res.data.data

            this.checkedGoodsList = data.checkedGoodsList;
            this.checkedAddress= data.checkedAddress;
            this.availableCouponLength= data.availableCouponLength;
            this.actualPrice= data.actualPrice;
            this.couponPrice= data.couponPrice;
            this.grouponPrice= data.grouponPrice;
            this.freightPrice= data.freightPrice;
            this.goodsTotalPrice= data.goodsTotalPrice;
            this.orderTotalPrice= data.orderTotalPrice;
            this.balance= data.balance;
            if (data.userLevel === 2) {
              // this.eyu = true
              this.isMj = true
            }

            setLocalStorage({AddressId: data.addressId, CartId: data.cartId, CouponId: data.couponId});

            getUserOrderStatus().then(e => {
              // console.log(e, '123333')
              // if (this.actualPrice > 1000 && data.userLevel === 2) {
              //   this.eyu = e.data.data
              //   this.actualPrice = this.actualPrice - parseInt((this.actualPrice / 1000) * 50)
              //   // console.log(parseInt((this.actualPrice / 1000) * 50), '333')
              // }
            })
          } else if(res.data.errno === 502) {
            Toast.fail(res.data.errmsg);
            this.$router.go(-1)
          }
      });
    },
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
      
      if(index === -1 ){
        setLocalStorage({CouponId: -1});
      }
      else{
        const couponId = this.coupons[index].id;
        setLocalStorage({CouponId: couponId});  
      }

      this.init()
    },
    onExchange() {
      this.$toast("兑换暂不支持");
    }    
  },

  components: { 
    [Dialog.name]: Dialog ,
    [Row.name]: Row ,
    [Col.name]: Col ,
    [RadioGroup.name]: RadioGroup ,
    [Radio.name]: Radio ,
    [Toast.name]: Toast ,
    [NavBar.name]: NavBar ,
    [SubmitBar.name]: SubmitBar,
    [Card.name]: Card,
    [Field.name]: Field,
    [Tag.name]: Tag,
    [CouponCell.name]: CouponCell,
    [CouponList.name]: CouponList,
    [Popup.name]: Popup
  }
};
</script>


<style lang="scss" scoped>
.order-coupon {
  margin-top: 10px;
}
.pay-icon {
  width: 25px;
}
/deep/.pay-list {
  .van-cell__value {
    position: absolute;
    left: 12px;
  }
  .van-cell__title {
    padding-left: 27px;
  }
}
.huabei {
  border: 1px solid #ccc;
  margin: -1px 0 0 -1px;
  font-size: 12px;
  z-index: 1;
  .fenqi span{
    font-size: 14px;
    color: #ff6600;
    margin-right: 5px;
  }
  .tit span{
    font-size: 18px;
    color: #ff6600;
    margin-right: 5px;
  }
  .tit2 {
    padding-bottom: 5px;
    margin-bottom: 5px;
    border-bottom: 1px solid #ddd;
  }
}
.selected {
  border:1px solid #ff6600;
  transform: translateX(0);
  z-index: 3;
  background: transparent url(http://www.dtw360.cn/plugs/ui-choose/src/icon-selected.png) no-repeat right bottom;
}
</style>